<?php
class Vfriend_Cache
{
	public static $groupkey = '';
	public static $isusecache = 1;
	public static $cache = null;
	public static $clear = null;
	public static $compression = true;

	public function __construct()
	{
		$objConf = new Zend_Config_Ini(ROOT_DIR . '/configs/config.ini', 'memcache');
		$objCache = new Memcache;
		foreach ($objConf as $cache=>$config) {
			$arrCacheConf = $config->toArray();			
			$objCache->addServer($arrCacheConf['host'], $arrCacheConf['port'], $arrCacheConf['persistent']);
		}
		$this->cache = $objCache;
		$this->clear = new Vfriend_Cache_Delete($this);
		$this->isusecache = 1;
		$this->groupkey = '';
	}

	public function setGroupKey($strGroupKey = '')
	{
		if ($strGroupKey) {
			$this->groupkey = $strGroupKey;
			$arrGroupKey = $this->cache->get($this->groupkey);
			if (!$arrGroupKey) {
				$this->cache->set($this->groupkey, array(), false, 0);			
			}
		}
	}
	
	public function deleteKeyCached()
	{
		if ($this->groupkey) {
			$this->cache->set($this->groupkey, array(), false, 0);
		}
	}
	
	public function updateKeyCached($arrGroupKey = array())
	{
		if ($this->groupkey) {			
			$this->cache->set($this->groupkey, $arrGroupKey, false, 0);			
		}
	}
	
	public function getKeyCached() 
	{
		if ($this->groupkey)  {
			$arrGroupKey = $this->get($this->groupkey);
			return $arrGroupKey;
		}
		return null;
	}
	
	public function setNoCache()
	{
		$this->isusecache = 0;
	}

	public function get($key)
	{
	
		if ($this->isusecache) {
			return Zend_Json::decode($this->cache->get($key));
		}
		return null;
	}

	public function set($key, $data, $expire = 0)
	{
		$data = Zend_Json::encode($data);		
		if ($this->isusecache) {
			if (!$data) {
				$data = VFRIEND_NOCACHE;
			} elseif ($this->groupkey)  {				
				$arrGroupKey = $this->cache->get($this->groupkey);
				if (!in_array($key, $arrGroupKey)) {
					$arrGroupKey[] = $key;
					$this->cache->set($this->groupkey, $arrGroupKey, false, 0);
				}
			}
			return $this->cache->set($key, $data, false, $expire);
		}
		return 0;
	}

	public function delete($key)
	{
		$key = is_array($key) ? $key : array($key);
		foreach ($key as $k=>$id) {
			$this->cache->delete($id);
		}
	}

	public function flush()
	{
		return $this->cache->flush();
	}
}
?>